/* $RCSFile: EnhancedLinksEdit.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/EnhancedLinks/EnhancedLinksEdit.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:20  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:53  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Security;
using AddonNice.UI;
using AddonNice.Helpers;
using AddonNice.Configuration;
using AddonNice.Settings.PageModules.EnhancedLink;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.EnhancedLinks
{
	public partial class EnhancedLinksEdit : AddonNice.UI.AddEditItemPage
    {
        EnhancedLinkDB enhancedLinksDB = new EnhancedLinkDB();

        string _UploadDirectory =   string.Empty;
        string UploadDirectory
        {
            get
            {
                if ( _UploadDirectory != string.Empty )
                    return _UploadDirectory;
                string PortalFullPath   =   portalSettings.PortalFullPath;
                if ( !PortalFullPath.EndsWith("/") )
                    PortalFullPath   +=   "/";
                _UploadDirectory        =   PortalFullPath +moduleSettingsDic[EStr.ENHANCEDLINKS_ICONPATH].ToString().Trim();
                if ( !_UploadDirectory.EndsWith("/") )
                    _UploadDirectory    +=   "/";
               return _UploadDirectory;
            }
        }

        public EnhancedLinksEdit() : base(true,true,true,true)
        {}

        /// <summary>
		/// The Page_Load event on this Page is used to obtain the 
		/// ItemID of the link to edit.
		/// It then uses the AddonNice.EnhancedLinkDB() data component
		/// to populate the page's edit controls with the links details.
		/// </summary>
        protected void Page_Load(object sender, System.EventArgs e) 
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedLinksEdit Page_Load BEG IsPostBack: {0}",IsPostBack),PageTraceSwitch.Sw.Info);
			
            Src.Text                                    =   Src.Text;
			Src.UploadDirectory                         =   UploadDirectory; // Must force because not saved in Viewstate

			if ( !IsPostBack ) 
            {
				TargetField.Items.Add(new RadComboBoxItem("_new"));
				TargetField.Items.Add(new RadComboBoxItem("_blank"));
				TargetField.Items.Add(new RadComboBoxItem("_parent"));
				TargetField.Items.Add(new RadComboBoxItem("_self"));
				TargetField.Items.Add(new RadComboBoxItem("_top"));

                if ( !isNewItem ) 
                {
                    // Obtain a single row of link information
                    SqlDataReader dr                    =   null;
					try
					{
						dr                              =   enhancedLinksDB.GetSingleEnhancedLinkGlobalized(ItemID);
						if (dr.Read())
						{
							TitleField.Text				=   (string)dr["Title"];
							DescriptionField.Text		=   (string)dr["Description"];
							string Url				    =   (string)dr["Url"];
							UrlField.Text				=   Url;
							string Source               =   (string)dr["ImageUrl"];
                            if ( Source.StartsWith(UploadDirectory) )
                                Source                  =   Source.Substring(UploadDirectory.Length);
                            Src.Text					=   Source;
							ViewOrderField.Text			=   dr["ViewOrder"].ToString();
							CreatedBy.Text				=   (string)dr["CreatedByUser"];
							CreatedDate.Text			=   ((DateTime)dr["CreatedDate"]).ToShortDateString();
                            string target               =  (string)dr["Target"];
							RadComboBoxItem itm         =   TargetField.Items.FindItemByText(target);
                            if ( itm != null )
                                itm.Selected = true;
                            else if ( !string.IsNullOrEmpty(target) )
                            {
                                itm                     =   new RadComboBoxItem(target);
                                TargetField.Items.Add(itm);
                                itm.Selected            =   true;
                            }
							IsGroup.Checked				=   false;
                            CbUsePageNum.Checked        =   false;
                            if ( PageTraceSwitch.Sw.TraceVerbose )
			                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedLinksEdit Page_Load Url: {0}, Target: {1}",Url,target),PageTraceSwitch.Sw.Info);
							if (Url.Equals(StStr.SEPARATOR))
							{
								oldUrl.Text             =   string.Empty;
							    IsGroup.Checked		    =   true;
							}
							else if (Url.StartsWith(StStr.INTERNAL,false,CultureInfo.InvariantCulture))
							{
								oldUrl.Text             =   string.Empty;
                                CbUsePageNum.Checked    =   true;
                                tabDropDownList.Visible =   true;
                                tabDropDownList.SelectedTreeViewValue   =   Url.Substring(9);
							}
							else
							{
								oldUrl.Text             =   UrlField.Text;
							}
                            tabDropDownList.DataBind();
							SetVisibility();
						}
					}
					catch (Exception ex)
					{
                        if ( PageTraceSwitch.Sw.TraceError )
						    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]EnhancedLinksEdit Page_Load ex : {0}",ex),PageTraceSwitch.Sw.Info);
                        throw;
					}
					finally
					{
						if (dr != null)
							dr.Close();
					}
                }
            }
            if ( PageTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedLinksEdit Page_Load END IsPostBack: {0}",IsPostBack),PageTraceSwitch.Sw.Info);
        }

		private void SetVisibility ()
		{
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedLinksEdit SetVisibility  BEG IsGroup.Checked: {0}, CbUsePageNum.Checked: {1}",IsGroup.Checked,CbUsePageNum.Checked),PageTraceSwitch.Sw.Info);
			if (IsGroup.Checked) 
			{
				UrlField.Text               =   StStr.SEPARATOR;
				UrlField.Visible            =   false;
				UrlFieldLabel.Visible       =   false;
				TargetField.Visible         =   false;
				TargetFieldLabel.Visible    =   false;
                CbUsePageNum.Visible        =   false;
                tabDropDownList.Visible     =   false;
			} 
			else if (CbUsePageNum.Checked) 
			{
				UrlField.Visible            =   false;
				UrlFieldLabel.Visible       =   false;
				TargetField.Visible         =   true;
				TargetFieldLabel.Visible    =   true;
                tabDropDownList.Visible     =   true;
			} 
			else 
			{
				UrlField.Visible            =   true;
				UrlFieldLabel.Visible       =   true;
				TargetField.Visible         =   true;
				TargetFieldLabel.Visible    =   true;
                CbUsePageNum.Visible        =   true;
                tabDropDownList.Visible     =   false;
			}
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]EnhancedLinksEdit SetVisibility  END.",PageTraceSwitch.Sw.Info);
		}

 		/// <summary>
		/// create or update a link.  It  uses the AddonNice.EnhancedLinkDB()
		/// data component to encapsulate all data functionality.
		/// </summary>
        void EnhancedLinksEdit_Update(object sender,AddonNice.UI.ADNPageEventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedLinksEdit EnhancedLinksEdit_Update BEG isNewItem: {0}",isNewItem),PageTraceSwitch.Sw.Info);
            // Create an instance of the EnhancedLink DB component
            string user             =   PortalSecurity.Wrapper.userName;
            string Url              =   UrlField.Text;
		    if (CbUsePageNum.Checked) 
                Url                 =   string.Format(StStr.INTERNALPARAM,tabDropDownList.SelectedValue);

            string target           =   TargetField.SelectedItem.Text;
            string Source           =   Src.Text;
            if ( Source.StartsWith(UploadDirectory) )
                    Source          =   Source.Substring(UploadDirectory.Length);
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedLinksEdit EnhancedLinksEdit_Update Url: {0}, Target: {1}, Source: {2}",Url,target,Source),PageTraceSwitch.Sw.Info);
            if ( isNewItem ) 
            {
                // Add the link within the Links table
                enhancedLinksDB.AddEnhancedLink(ModuleID, ItemID, user, TitleField.Text, Url, Int32.Parse(ViewOrderField.Text), DescriptionField.Text, Source, 0, target);
            }
            else 
            {
                // Update the link within the Links table
                enhancedLinksDB.UpdateEnhancedLinkGlobalized(ModuleID, ItemID, user, TitleField.Text, Url, Int32.Parse(ViewOrderField.Text), DescriptionField.Text, Source, 0, target);
            }
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]EnhancedLinksEdit EnhancedLinksEdit_Update END.",PageTraceSwitch.Sw.Info);
        }

		/// <summary>
		/// a link.  It  uses the AddonNice.EnhancedLinkDB()
		/// data component to encapsulate all data functionality.
		/// </summary>
        void EnhancedLinksEdit_Delete(object sender,AddonNice.UI.ADNPageEventArgs e)
        {
            // Only attempt to delete the item if it is an existing item
            // (new items will have "ItemID" of 0)
            if ( !isNewItem ) 
            {
                enhancedLinksDB.DeleteEnhancedLink(ItemID);
            }
		}

        void CbUsePageNum_CheckedChanged(object sender,EventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedLinksEdit CbUsePageNum_CheckedChanged BEG CbUsePageNum.Checked: {0}",CbUsePageNum.Checked),PageTraceSwitch.Sw.Info);
			if (CbUsePageNum.Checked) 
			{
				oldUrl.Text         =   UrlField.Text;
				tabDropDownList.SelectedTreeViewValue   =   StStr.PageDemoWebID.ToString();
                UrlField.Text       =   string.Format(StStr.INTERNALPARAM,StStr.PageDemoWebID);
                tabDropDownList.DataBind();
                if ( tabDropDownList.SelectedValue != null )
                    UrlField.Text   =   string.Format(StStr.INTERNALPARAM,tabDropDownList.SelectedValue);
			} 
			else 
			{
				UrlField.Text       =   oldUrl.Text;
			}
			SetVisibility ();
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]EnhancedLinksEdit CbUsePageNum_CheckedChanged END.",PageTraceSwitch.Sw.Info);
        }

        void IsGroup_CheckedChanged(object sender, EventArgs e)
        {
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedLinksEdit IsGroup_CheckedChanged BEG IsGroup.Checked: {0}",IsGroup.Checked),PageTraceSwitch.Sw.Info);
			if (IsGroup.Checked) 
			{
				UrlField.Text       =   StStr.SEPARATOR;
			} 
			else 
			{
                CbUsePageNum_CheckedChanged(sender,e);
            }
			SetVisibility ();
            if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]EnhancedLinksEdit IsGroup_CheckedChanged END.",PageTraceSwitch.Sw.Info);
		}

        #region Std Overrides

        /// <summary>
        /// Here we create the command buttons and add them to the PlaceHolders prepared
        /// </summary>
        override protected void OnPreInit(EventArgs e)
        {
			if ( PageTraceSwitch.Sw.TraceVerbose )
    			Trace2.WriteLine("[V]EnhancedLinksEdit OnPreInit BEG.",PageTraceSwitch.Sw.Info);
            MasterPage m            =   Master; // bug asp.net with matserpages, controls not instanciated if master not called
            if ( isNewItem ) 
                PageHasDeleteBtn    =   false;
			if (PageTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]EnhancedLinksEdit OnPreInit PageHasDeleteBtn: {0}.",PageHasDeleteBtn),PageTraceSwitch.Sw.Info);
            base.OnPreInit(e);
			if ( PageTraceSwitch.Sw.TraceVerbose )
			    Trace2.WriteLine("[V]EnhancedLinksEdit OnPreInit END.",PageTraceSwitch.Sw.Info);
        }

        override protected void OnInit(EventArgs e)
        {
			if ( PageTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]EnhancedLinksEdit OnInit BEG.",PageTraceSwitch.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
			if ( PageTraceSwitch.Sw.TraceVerbose )
    			Trace2.WriteLine("[V]EnhancedLinksEdit OnInit END.",PageTraceSwitch.Sw.Info);
        }

        private void InitializeComponent() 
        {    
			Load	                    +=  new EventHandler(Page_Load);
            Delete                      +=  new PageEventHandler(EnhancedLinksEdit_Delete);
            Update                      +=  new PageEventHandler(EnhancedLinksEdit_Update);
            IsGroup.CheckedChanged      +=  new EventHandler(IsGroup_CheckedChanged);
            IsGroup.AutoPostBack        =   true;
            CbUsePageNum.CheckedChanged += new EventHandler(CbUsePageNum_CheckedChanged);
            CbUsePageNum.AutoPostBack   =   true;
		}

        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons
        {
            get { return PlaceHolderButtons; }
            set { }
        }

        protected override System.Web.UI.WebControls.PlaceHolder placeHolderForButtons2
        {
            get { return PlaceHolderButtons2; }
            set { }
        }

		#endregion
    }
}
